'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-08-13 10:42:38
@LastEditTime: 2020-02-18 17:16:43
@LastEditors: Please set LastEditors
'''
from ...models.service_manage import ServiceItem, ServiceOption, ServiceOrder, ServicePackage, ServiceProvider, ServiceRecord
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.data import dataframe_to_list
from ...service.buss_pub.bill_manage import BillManageService, OperationType, Status, TypeId
from ...service.common import get_info, execute_python, update_data
from server.pao_python.pao.data import string_to_date, date_to_string
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
import pandas as pd
import uuid
import copy
import datetime
from .service_detail import ServiceProductDetailService
from ...pao_python.pao.data import process_db
'''
说明
 1、app服务列表服务
'''


class ServicePackageListService(MongoService):
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.detail_service = ServiceProductDetailService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def get_service_package_list(self):
        '''获取服务包列表'''
        _filter = MongoBillFilter()
        _filter.lookup('PT_User', 'organization', 'id', 'org')\
            .add_fields({'organization_name': '$org.name'})\
            .match((C('bill_status') == 'valid')).project({'_id': 0, 'org._id': 0})
        res = self.query(_filter, 'PT_Service_Item_Package')
        for result in res:
            total_price = 0
            for service_item in result.get('service_item'):
                if service_item.get('service_options'):
                    for option in service_item.get('service_options'):
                        _filter_opt = MongoFilter()
                        _filter_opt.match((C('bill_status') == 'valid') & (
                            C('id') == option.get('id'))).project({'_id': 0})
                        res_opt = self.query(_filter_opt, 'PT_Service_Option')
                        if res_opt:
                            option['name'] = res_opt[0].get('name')
                            if not option['value']:
                                option['value'] = res_opt[0].get(
                                    'default_value')  # 以后是要去掉的，因为选项没有默认值
                        else:
                            option['name'] = ''
                _filter_item = MongoFilter()
                _filter_item.match((C('bill_status') == 'valid') & (
                    C('id') == service_item.get('service_item'))).project({'_id': 0})
                res_item = self.query(_filter_item, 'PT_Service_Item')
                item_price = execute_python(res_item[0].get(
                    'valuation_formula'), service_item.get('service_options'))
                total_price += float(item_price)
            result["total_price"] = total_price
        return res

    def __get_service_product(self, ids):
        '''获取下一级的服务产品信息'''
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'organization_id', 'id', 'org_info')\
            .add_fields({'organization_name': '$org_info.name'})\
            .match_bill((C('state') == 1) & ((C('id') == ids))).project({'_id': 0, 'org_info._id': 0})
        res = self.query(_filter, 'PT_Service_Product')
        if res:
            if res[0].get('service_item_id') and res[0].get('valuation_formula'):
                return res
        #     elif res[0].get('product_collection'):
        #         res_list = []
        #         for product in res[0].get('product_collection'):
        #             res_product = self.__get_service_product(product)
        #             res_list.append(res_product)
        #         return res_list
        return res

    def get_service_product_package_list(self, condition, page, count):
        '''获取服务产品套餐列表'''
        keys = ['organization_id', 'id', 'name', 'is_catering',
                'service_product_type', 'sort', 'name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'organization_id', 'id', 'org_info')\
            .add_fields({'organization_name': '$org_info.name'})\
            .match_bill((C('state') == 1)
                        & (C('is_external') == '1')
                        & (C('is_service_item') == 'false')
                        & (C('service_product_type') == values['service_product_type'])
                        & (C('organization_id') == values['organization_id'])
                        & (C('id') == values['id'])
                        & (C('name').like(values['name']) | C('org_info.name').like(values['name'])))\
            .lookup_bill('PT_Service_Order', 'id', 'detail.product_id', 'order_info')\
            .add_fields({'pay_count': self.ao.size('$order_info'), 'total_price': '$service_package_price'})\
            .lookup_bill('PT_Service_Order_Comment', 'id', 'product_id', 'comment')\
            .add_fields({'comment_all': self.ao.summation('$comment.service_quality')})\
            .add_fields({'length': self.ao.size('$comment')})\
            .add_fields({'comment_avg': self.ao.floor(self.ao.switch([self.ao.case(((F('length') == 0)), 0)], (F('comment_all').__truediv__('$length')).f))})\
            .project({'_id': 0, 'org_info._id': 0, 'order_info._id': 0, 'comment._id': 0})
        if 'sort' in condition and condition['sort'] != None and 'num' in condition and condition['num'] != None:
            if condition['sort'] == '销量':
                _filter.sort({'pay_count': condition['num']})
            elif condition['sort'] == '价格':
                _filter.sort({'service_package_price': condition['num']})
            else:
                _filter.sort({'create_date': -1})
        res = self.page_query(_filter, 'PT_Service_Product', page, count)
        # if res.get('result'):
        #     for product in res['result']:
        #         pruduct_detail = self.detail_service.get_service_product_package_detail(
        #             {'id': product.get('id')})
        #         # print(pruduct_detail)
        #         product['total_price'] = 0
        #         if len(pruduct_detail) > 0 and 'total_price' in pruduct_detail[0]:
        #             product['total_price'] = pruduct_detail[0].get(
        #                 'total_price')
        #         if len(pruduct_detail) > 0 and 'pay_count' in pruduct_detail[0]:
        #             product['pay_count'] = pruduct_detail[0].get('pay_count')
        return res
